/**
 * 该文件是用来操作登录、注册、获取用户信息、token 等操作，
 * 📢🔈📣几乎全部需要重写，不分析了 ❗❗❗
 */

import { defineStore } from 'pinia'

// 导入操作 Token 的方法
import { getToken, removeToken, setToken } from '../utils/token-utils'
import type { UserInfoState } from './interface'
import { ElMessage } from 'element-plus'
import { staticRoutes } from '@/router/routes'
import { reqLogin } from '@/api/user'

/**
 * 用户信息
 * @methods setUserInfos 设置用户信息
 */
export const useUserInfoStore = defineStore('userInfo', {
  state: (): UserInfoState => ({
    token: getToken() as string,
    name: '',
    avatar: '',
    menuRoutes: []
  }),

  actions: {
    // 登录
    async login(username: string, password: string) {
      const res = await reqLogin(username, password)
      if (res.code === 20000) {
        // 成功
        // 存储token和将token放到state中
        setToken(res.data.token)
        this.token = res.data.token
        // 登录成功
        Promise.resolve(true)
      } else {
        // 登录失败
        Promise.resolve(false)
      }
    },

    // 获取用户信息
    getInfo() {
      return new Promise((resolve, reject) => {
        setTimeout(() => {
          this.name = 'admin'
          this.avatar = 'https://wpimg.wallstcn.com/f778738c-e4f8-4870-b634-56703b4acafe.gif'
          this.menuRoutes = staticRoutes
          resolve({ name: this.name, avatar: this.avatar, token: this.token })
        }, 1000)
      })
    },

    // 退出功能
    reset() {
      // 删除local中保存的token
      removeToken()
      // 提交重置用户信息的mutation
      this.token = ''
      this.name = ''
      this.avatar = ''
    }
  }
})
